package networkTraining.convergence;

import java.util.LinkedList;
import java.util.List;

import networkTraining.epoch.IEpochExecutor;

public class WindowConvergenceTest implements IConvergenceTest
{
	private int windowSize;
	private List<Double> rmsErrorWindow1;
	private List<Double> rmsErrorWindow2;
	private double currentError;
	private double windowDelta;

	public WindowConvergenceTest(int windowSize)
	{
		this.windowSize = windowSize;

		rmsErrorWindow1 = new LinkedList<Double>();
		rmsErrorWindow2 = new LinkedList<Double>();
		for (int i = 0; i < windowSize; i++)
		{
			rmsErrorWindow1.add(1.0);
			rmsErrorWindow2.add(1.0);
		}

	}

	@Override
	public boolean isNetworkConverged(IEpochExecutor epochExecutor)
	{
		currentError = epochExecutor.getEpochRMSError();

		rmsErrorWindow1.remove(0);
		rmsErrorWindow1.add(rmsErrorWindow2.remove(0));
		rmsErrorWindow2.add(currentError);

		double windowAverageError1 = 0;
		double windowAverageError2 = 0;
		for (int i = 0; i < windowSize; i++)
		{
			windowAverageError1 += rmsErrorWindow1.get(i);
			windowAverageError2 += rmsErrorWindow2.get(i);
		}

		windowAverageError1 /= windowSize;
		windowAverageError2 /= windowSize;
		
		windowDelta = windowAverageError1 - windowAverageError2;

		System.out.printf("Current Error: %.17f, window1: %.17f, window2: %.17f, delta: %.17f\n", currentError,
		    windowAverageError1, windowAverageError2, windowDelta);

		if (windowDelta < 0)
			return true;
		else
			return false;

	}
}

